-- UISellItemConfirm
-- Create by chengb Dec/9/2014
-- 出售物品提示框界面

local LONG_PRESS_TIME      = 1.0   -- 按钮是否长按时间判定（秒）
local AUTO_CHANGE_INTERVAL = 0.1   -- 自动增减出售数量的时间间隔（秒）

-- UISellItemConfirm继承自Layer
UISellItemConfirm = class("UISellItemConfirm", function()
    return cc.Layer:create();
end)

-- @param classId      物品id
-- @param itemName     物品名称
-- @param rarity       物品稀有度
-- @param maxAmount    可出售的物品最大数量
-- @param itemIcon     物品图标路径
-- @param price        物品单价
-- @param payAttrib    支付方式(如：gem, money)
-- @param okFunc       点击确认的处理函数
-- @param args         okFunc所需的参数列表（当参数超过1个时，这里通常传入table类型）
-- @param okText       确认按钮文本(默认显示'确认')
function UISellItemConfirm.create(classId, itemName, rarity, maxAmount, itemIcon, price, payAttrib, okFunc, args, okText)
    return UISellItemConfirm.new(classId, itemName, rarity, maxAmount, itemIcon, price, payAttrib, okFunc, args, okText);
end

-- 内部函数声明
local addSellAmount;
local reduceSellAmount;
local autoChangeSellAmount;
local resize;
local redrawSellAmount;
local redrawItemStar;

-- 构造函数
function UISellItemConfirm:ctor(classId, itemName, rarity, maxAmount, itemIcon, price, payAttrib, okFunc, args, okText)
    -- 初始化
    local node = cc.CSLoader:createNode("layout/dialog/SellItemConfirm.csb");
    self:addChild(node);
    self.price = price;
    self.maxAmount = maxAmount;
    self.sellAmount = 1;        -- 默认出售1件

    local panel = findChildByName(node, "img_panel");

    -- 设置物品名称（需要设置描边）
    local itemNameLabel = panel:getChildByName("item_name");
    itemNameLabel:setString(itemName);
    TextStyleM.setOutlineStyle(itemNameLabel);

    -- 设置物品图标
    local itemImg = findChildByName(panel, "item_frame/item_icon");
    itemImg = replaceImageView(itemImg);
    itemImg:loadTexture(itemIcon);

    -- 设置物品稀有度
    local itemFrame = panel:getChildByName("item_frame");
    redrawItemStar(itemFrame, rarity);

    -- 设置拥有物品数量
    local ownAmountLabel = panel:getChildByName("own_amount");
    ownAmountLabel:setString(string.format(getLocStr("own_item_amount"), maxAmount));

    -- 设置出售数量
    local sellAmountLabel = panel:getChildByName("item_num");
    self.sellAmountLabel = sellAmountLabel;
    sellAmountLabel:setString(self.sellAmount .. "/" .. maxAmount);

    local gainBar = panel:getChildByName("gain_bar");
    local gainBriefLabel = gainBar:getChildByName("gain_brief");

    -- 设置获得的属性和图标
    local costImg = gainBar:getChildByName("gain_img");
    if payAttrib == "money" then
        local attribName = getLocStr("money");
        gainBriefLabel:setString(getLocStr("sell_1") .. attribName);
        TextStyleM.setOutlineStyle(gainBriefLabel);   -- 设置描边
        costImg:loadTexture(getMoneyIconPath());
    elseif payAttrib == "gem" then
        local attribName = getLocStr("gem");
        gainBriefLabel:setString(getLocStr("sell_1") .. attribName);
        TextStyleM.setOutlineStyle(gainBriefLabel);   -- 设置描边
        costImg:loadTexture(getGoldIconPath());
    else
        error("暂不支持属性：" .. payAttrib);
    end

    -- 设置获得的金钱总数
    local attribAmountLabel = gainBar:getChildByName("amount");
    self.attribAmountLabel = attribAmountLabel;
    attribAmountLabel:setString("" .. self.sellAmount * self.price);

    -- 设置最大按钮文本（CocosStudio编辑器上设置的文字显示乱码，这里只好重新设置一边了）
    local maxBtn = panel:getChildByName("btn_max");
    maxBtn:setTitleText(getLocStr("maximum"));

    local okBtn = panel:getChildByName("btn_ok");
    if type(okText) == 'string' then
        okBtn:setTitleText(okText);
    else
        okBtn:setTitleText("确认");
    end

    -- 注册确认按钮点击事件
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_select");
            if type(okFunc) == 'function' then
                okFunc(classId, self.sellAmount);
            end
            -- 移除提示框
            UIMgr.getCurrentScene():removeDialog(self);
        end
    end
    okBtn:addTouchEventListener(onOkClick);

    -- 注册取消按钮点击事件
    local canelBtn = panel:getChildByName("btn_cancel")
    local function onCancelClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 移除提示框
            UIMgr.getCurrentScene():removeDialog(self);
        end
    end
    AddBackEventHandler(self, canelBtn, onCancelClick);

    -- 注册增加按钮点击事件
    local addBtn = panel:getChildByName("btn_add");
    local function onAddClick(sender, eventType)
        -- 停止所有动作
        sender:stopAllActions();

        -- 已达最大值，不处理
        if self.sellAmount >= self.maxAmount then
            return;
        end

        if eventType == ccui.TouchEventType.began then
            -- 定时开启增加出售数量
            performWithDelay(sender, function() autoChangeSellAmount(self, sender, true) end, LONG_PRESS_TIME);
        elseif eventType == ccui.TouchEventType.ended then
            -- 增加出售数量
            addSellAmount(self);
        end
    end
    addBtn:addTouchEventListener(onAddClick);

    -- 注册减少按钮点击事件
    local reduceBtn = panel:getChildByName("btn_reduce");
    local function onReduceClick(sender, eventType)
        -- 停止所有动作
        sender:stopAllActions();

        -- 已达最小值，不处理
        if self.sellAmount <= 1 then
            return;
        end

        if eventType == ccui.TouchEventType.began then
            -- 定时减少出售数量
            performWithDelay(sender, function() autoChangeSellAmount(self, sender, false); end, LONG_PRESS_TIME);
        elseif eventType == ccui.TouchEventType.ended then
            -- 减少出售数量
            reduceSellAmount(self);
        end
    end
    reduceBtn:addTouchEventListener(onReduceClick);

    -- 注册最大按钮点击事件
    local function onMaxClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 已达最大值，不处理
            if self.sellAmount >= self.maxAmount then
                return;
            end

            -- 刷新出售数量
            self.sellAmount = self.maxAmount;
            redrawSellAmount(self);
        end
    end
    maxBtn:addTouchEventListener(onMaxClick);

    -- 设置按钮标题的描边
    TextStyleM.setOutlineStyle(okBtn:getTitleRenderer());
    TextStyleM.setOutlineStyle(canelBtn:getTitleRenderer());

    -- 重新调整布局
    resize(node);
end

-- 重新调整布局
resize = function(node)
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    -- 调整拥有物品数量的位置
    local panel = findChildByName(node, "img_panel");
    local itemNameLabel  = panel:getChildByName("item_name");
    local ownAmountLabel = panel:getChildByName("own_amount");
    local posX = itemNameLabel:getPositionX() + itemNameLabel:getContentSize().width + 40;
    ownAmountLabel:setPositionX(posX);

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- 确认框居中并缩放到合适大小
    AlignM.alignToCenter(node, "img_panel");
end

-- 刷新出售数量
function redrawSellAmount(self)
    local attribAmount = self.price * self.sellAmount;
    self.sellAmountLabel:setString(self.sellAmount .. "/" .. self.maxAmount);
    self.attribAmountLabel:setString("" .. attribAmount);
end

-- 自动增减出售数量
function autoChangeSellAmount(self, sender, isAdd)
    if isAdd then
        addSellAmount(self);
    else
        reduceSellAmount(self);
    end

    -- 间隔 AUTO_CHANGE_INTERVAL 秒自动增减出售数量
    -- 注：如果在此期间触发了任何按钮触摸事件，所有动作都会被stopAllActions取消
    performWithDelay(sender, function() autoChangeSellAmount(self, sender, isAdd) end, AUTO_CHANGE_INTERVAL)
end

-- 增长出售数量
function addSellAmount(self)
    self.sellAmount = math.min(self.maxAmount, self.sellAmount + 1);
    redrawSellAmount(self);
end

-- 减少出售数量
function reduceSellAmount(self)
    self.sellAmount = math.max(1, self.sellAmount - 1);
    redrawSellAmount(self);
end

-- 显示商品星级（稀有度）
function redrawItemStar(starParent, rarity)
    -- 显示物品星级
    for i = 1, MAX_ITEM_RARITY do
        local star = starParent:getChildByName("star" .. i);
        if type(rarity) ~= "number" then
            star:setVisible(false);
        elseif i <= rarity then
            star:setVisible(true);
        else
            star:setVisible(false);
        end
    end
end

return UISellItemConfirm;

